package cn.woblog.android.downloader;

import java.util.Observer;

import android.content.Context;
import android.content.Intent;
import cn.woblog.android.downloader.domain.DownloadInfo;
import cn.woblog.android.downloader.domain.DownloadStatus;
import cn.woblog.android.downloader.observable.DataChanger;
import cn.woblog.android.downloader.service.DownloadService;
import cn.woblog.android.downloader.utils.Consts;

public class DownloadManager {
	private static DownloadManager instances;
	private Context context;
	private DataChanger dataChanger;

	public DownloadManager(Context context) {
		this.context = context;
		dataChanger = DataChanger.getInstance(context);
		context.startService(new Intent(context, DownloadService.class));
	}

	public static DownloadManager getInstance(Context context) {
		if (instances == null) {
			instances = new DownloadManager(context);
		}
		return instances;
	}

	public void toIntent(DownloadInfo info, DownloadStatus status) {
		Intent intent = new Intent(context, DownloadService.class);
		intent.putExtra(Consts.KEY_DATA, info);
		intent.putExtra(Consts.KEY_ACTION, status.name());
		context.startService(intent);
	}

	public void toIntent(String id, DownloadStatus status) {
		Intent intent = new Intent(context, DownloadService.class);
		intent.putExtra(Consts.KEY_DATA, id);
		intent.putExtra(Consts.KEY_ACTION, status.name());
		context.startService(intent);
	}

	public void add(DownloadInfo info) {
		toIntent(info, DownloadStatus.ADD);
		// Intent intent = new Intent(context, DownloadService.class);
		// intent.putExtra(Consts.KEY_DATA, info);
		// intent.putExtra(Consts.KEY_ACTION, DownloadStatus.ADD.name());
		// context.startService(intent);
	}

	public void pause(String id) {
		toIntent(id, DownloadStatus.PAUSE);
	}

	public void resume(String id) {
		toIntent(id, DownloadStatus.RESUME);
	}

	public void delete(String id) {
		toIntent(id, DownloadStatus.DELETE);
	}

	public void addObserver(Observer observer) {
		dataChanger.addObserver(observer);
		dataChanger.startNotifyLooper();
	}

	public void removeObserver(Observer observer) {
		dataChanger.deleteObserver(observer);
	}

	public void removeObservers() {
		dataChanger.deleteObservers();
	}
}
